var mongoose = require('mongoose'),
	ChatSchema = new mongoose.Schema({
		id:  String,
		listMessage:[{
			time : Number,
			idUser : String,
			isRead : Number,
			message : String
		}]
	});

ChatSchema.methods = {
	LoadHistory : function(ownerId, targetId, limit){
		this.model('Chat').find({'id': this.GetIdChat(ownerId, targetId)}).limit(limit).exec(function (err, docs) {
			console.log(docs);
			return docs;
		});
	},

	NewChat : function(ownerId, targetId){
		var id = this.GetIdChat(ownerId, targetId);
		this.model('Chat').findOne({'id': id}).exec(function(err, doc){
			if(err){
				this.model('Chat').create({
					id : id,
					listMessage : []
				}, function(err){

				});
			}
		});
	},

	NewMessage : function(ownerId, targetId, chatId, ip, time, offine, message){
		this.model('Chat').update({id: this.GetIdChat(ownerId, targetId)},
								{$push: { listMessage: {time: time, idUser : chatId, isRead : 1, message : message} } });
	},

	GetIdChat : function(ownerId, targetId){
		return ownerId > targetId ? targetId + '.' + ownerId : ownerId + '.' + targetId;
	}
}

module.exports = mongoose.model('Chat', ChatSchema);